// run: $exec < input
#include <iostream>
#include <cstring>

long long const maxl = 62;
long long a[maxl + 6];
long long b[maxl + 6];

long long way[maxl + 6];

long long n, k;

int main()
{
	long long T; std::cin >> T;
	while (T--) {
		std::cin >> n >> k;
		std::memset(b, 0, sizeof(0));
		long long tn = n;
		way[0] = 1;
		for (long long i = 1; i <= maxl; i++) {
			a[i] = tn & 1;
			tn /= 2;
			if (a[i] == 1) {
				b[i] = 0;
				way[i] = way[i - 1];
			} else way[i] = way[i - 1] * 2;
		}


		//for (long long i = 1; i <= maxl; i++) std::cout << a[i] << ' '; std::cout << '\n';


		long long p = maxl;
		for (long long i = p; i > 0; i--) {
			if (a[i] == 1) continue;
			if (way[i - 1] <= k) {
				b[i] = 1;
				k -= way[i - 1];
			} else b[i] = 0;
		}


		//for (long long i = 1; i <= maxl; i++) std::cout << b[i] << ' '; std::cout << '\n';

		long long ans = 0, p2 = 1;
		for (long long i = 1; i <= maxl; i++)
			ans += b[i] * p2, p2 *= 2;
		std::cout << ans << '\n';
	}
}

